//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.point.controller;

import ciicos.base.ActionResult;
import ciicos.base.UserInfo;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.exception.DataException;
import ciicos.iview.service.IviewService;
import ciicos.point.entity.PointNodeEntity;
import ciicos.point.entity.PointSyncEntity;
import ciicos.point.model.pointnode.PointNodeForm;
import ciicos.point.model.pointnode.PointNodeInfoVO;
import ciicos.point.model.pointnode.PointNodeListVO;
import ciicos.point.model.pointnode.PointNodePagination;
import ciicos.point.model.pointsync.PointSyncPagination;
import ciicos.point.result.ScadaEntity;
import ciicos.point.result.ScadaNode;
import ciicos.point.result.ScadaPointPagination;
import ciicos.point.service.PointNodeService;
import ciicos.point.service.PointSyncService;
import ciicos.util.DateUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.RandomUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(
    tags = {"点位节点"},
    value = "pointManage"
)
@RequestMapping({"/api/pointManage/PointNode"})
public class PointNodeController {
    private static final Logger log = LoggerFactory.getLogger(PointNodeController.class);
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private PointNodeService pointNodeService;
    @Autowired
    private Executor threadPoolExecutor;
    @Autowired
    private PointSyncService pointSyncService;
    @Autowired
    private IviewService iviewService;

    @ApiOperation("获取列表")
    @PostMapping({"/getList"})
    public ActionResult list(@RequestBody PointNodePagination pointNodePagination) throws IOException {
        List<PointNodeEntity> list = this.pointNodeService.getList(pointNodePagination);
        List<PointNodeListVO> listVO = JsonUtil.getJsonToList(list, PointNodeListVO.class);

        for(PointNodeListVO pointNodeVO : listVO) {
            pointNodeVO.setRoleid_name(this.generaterSwapUtil.getRoleSelect(pointNodeVO.getRoleid()));
            pointNodeVO.setCreatoruserid_name(this.generaterSwapUtil.userSelectValue(pointNodeVO.getCreatoruserid()));
            pointNodeVO.setCreatortime_name(pointNodeVO.getCreatortime());
            pointNodeVO.setJsonparam_name(pointNodeVO.getJsonparam());
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = (PaginationVO)JsonUtil.getJsonToBean(pointNodePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid PointNodeForm pointNodeForm) throws DataException {
        String b = this.pointNodeService.checkForm(pointNodeForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        } else {
            String mainId = RandomUtil.uuId();
            UserInfo userInfo = this.userProvider.get();
            pointNodeForm.setCreatoruserid(userInfo.getUserId());
            pointNodeForm.setCreatortime(DateUtil.getNow());
            PointNodeEntity entity = (PointNodeEntity)JsonUtil.getJsonToBean(pointNodeForm, PointNodeEntity.class);
            entity.setId(mainId);
            this.pointNodeService.save(entity);
            return ActionResult.success("创建成功");
        }
    }

    @DeleteMapping({"/batchRemove/{ids}"})
    @Transactional
    @ApiOperation("批量删除")
    public ActionResult batchRemove(@PathVariable("ids") String ids) {
        String[] idList = ids.split(",");
        int i = 0;

        for(String allId : idList) {
            this.delete(allId);
            ++i;
        }

        return i == 0 ? ActionResult.fail("删除失败") : ActionResult.success("删除成功");
    }

    @ApiOperation("信息")
    @GetMapping({"/{id}"})
    public ActionResult<PointNodeInfoVO> info(@PathVariable("id") String id) {
        PointNodeEntity entity = this.pointNodeService.getInfo(id);
        PointNodeInfoVO vo = (PointNodeInfoVO)JsonUtil.getJsonToBean(entity, PointNodeInfoVO.class);
        vo.setCreatoruserid(this.generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        if (vo.getCreatortime() != null) {
            vo.setCreatortime(vo.getCreatortime());
        }

        return ActionResult.success(vo);
    }

    @ApiOperation("表单信息(详情页)")
    @GetMapping({"/detail/{id}"})
    public ActionResult<PointNodeInfoVO> detailInfo(@PathVariable("id") String id) {
        PointNodeEntity entity = this.pointNodeService.getInfo(id);
        PointNodeInfoVO vo = (PointNodeInfoVO)JsonUtil.getJsonToBean(entity, PointNodeInfoVO.class);
        vo.setRoleid(this.generaterSwapUtil.getRoleSelect(vo.getRoleid()));
        vo.setCreatoruserid(this.generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        vo.setCreatortime(vo.getCreatortime());
        vo.setJsonparam(vo.getJsonparam());
        return ActionResult.success(vo);
    }

    @PutMapping({"/{id}"})
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid PointNodeForm pointNodeForm) throws DataException {
        String b = this.pointNodeService.checkForm(pointNodeForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        } else {
            PointNodeEntity entity = this.pointNodeService.getInfo(id);
            if (entity != null) {
                PointNodeEntity subentity = (PointNodeEntity)JsonUtil.getJsonToBean(pointNodeForm, PointNodeEntity.class);
                subentity.setCreatoruserid(entity.getCreatoruserid());
                subentity.setCreatortime(entity.getCreatortime());
                boolean b1 = this.pointNodeService.updateById(subentity);
                return !b1 ? ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据") : ActionResult.success("更新成功");
            } else {
                return ActionResult.fail("更新失败，数据不存在");
            }
        }
    }

    @ApiOperation("删除")
    @DeleteMapping({"/{id}"})
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        PointNodeEntity entity = this.pointNodeService.getInfo(id);
        if (entity != null) {
            this.pointNodeService.delete(entity);
        }

        return ActionResult.success("删除成功");
    }

    @ApiOperation("获取当前用户角色关联数据")
    @GetMapping({"/getByRole"})
    public ActionResult<List<PointNodeListVO>> getByRole() {
        UserInfo operatorUser = this.userProvider.get();
        if (operatorUser.getIsAdministrator()) {
            return ActionResult.fail(999, "当前用户为超级管理员");
        } else if (operatorUser.getRoleIds() != null && !operatorUser.getRoleIds().isEmpty()) {
            List<PointNodeEntity> list = this.pointNodeService.getByRoles(operatorUser.getRoleIds());
            if (list != null && !list.isEmpty()) {
                List<PointNodeListVO> listVO = JsonUtil.getJsonToList(list, PointNodeListVO.class);

                for(PointNodeListVO pointNodeVO : listVO) {
                    this.info(pointNodeVO.getId());
                    pointNodeVO.setRoleid_name(this.generaterSwapUtil.getRoleSelect(pointNodeVO.getRoleid()));
                    pointNodeVO.setCreatoruserid_name(this.generaterSwapUtil.userSelectValue(pointNodeVO.getCreatoruserid()));
                    pointNodeVO.setCreatortime_name(pointNodeVO.getCreatortime());
                    pointNodeVO.setJsonparam_name(pointNodeVO.getJsonparam());
                }

                return ActionResult.success(listVO);
            } else {
                return ActionResult.fail(221, "未找用户角色对应节点数据，请联系管理员进行设置");
            }
        } else {
            return ActionResult.fail(220, "当前用户未配置角色，请联系管理员进行设置");
        }
    }

    @ApiOperation("根据roleId查询")
    @GetMapping({"/getByRole/{roleId}"})
    public ActionResult getByRole(@PathVariable("roleId") String roleId) {
        PointNodeEntity entity = this.pointNodeService.getByRole(roleId);
        return entity == null ? ActionResult.fail(221, "未找用户角色对应节点数据，请联系管理员进行设置") : ActionResult.success(entity);
    }

    @ApiOperation("查询全部节点")
    @GetMapping({"/getRoot"})
    public Map<String, Object> getRoot() {
        Map<String, Object> map = new HashMap();
        PointNodeEntity entity = this.pointNodeService.getByRole("root");
        if (entity == null) {
            map.put("code", 200);
            return map;
        } else if (entity.getJsonparam() == null) {
            map.put("code", 400);
            map.put("msg", "暂未同步节点数据");
            return map;
        } else {
            map = JsonUtil.stringToMap(entity.getJsonparam());
            map.put("code", 200);
            return map;
        }
    }

    @ApiOperation("遍历显示节点下所以点位")
    @PostMapping({"/getPointByNode"})
    public ActionResult getPointByNode(@RequestBody PointSyncPagination pointSyncPagination) {
        pointSyncPagination.setDataType("0");
        pointSyncPagination.setCode(pointSyncPagination.getName());
        pointSyncPagination.setName(pointSyncPagination.getDesc());
        List<PointSyncEntity> list = this.pointSyncService.getList(pointSyncPagination);
        List<ScadaEntity> entityList = new ArrayList();

        for(PointSyncEntity pointSyncEntity : list) {
            ScadaEntity entity = new ScadaEntity();
            entity.setKIND(Integer.parseInt(pointSyncEntity.getType()));
            entity.setTag(pointSyncEntity.getCode());
            entity.setDESC(pointSyncEntity.getName());
            if (pointSyncEntity.getType().equals("2")) {
                entity.setName(pointSyncEntity.getCode() + ".TOTAL");
            } else if (pointSyncEntity.getType().equals("16")) {
                entity.setName(pointSyncEntity.getCode() + ".TEXT");
            } else {
                entity.setName(pointSyncEntity.getCode() + ".PV");
            }

            entity.setUNIT(pointSyncEntity.getUnit());
            entityList.add(entity);
        }

        PageListVO vo = new PageListVO();
        vo.setList(entityList);
        PaginationVO page = (PaginationVO)JsonUtil.getJsonToBean(pointSyncPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    @ApiOperation("获取默认时间区间")
    @GetMapping({"/getDefaultDateZone"})
    public ActionResult getDefaultDateZone() {
        Date endTime = new Date();
        Date startTime = DateUtil.dateAddHours(endTime, -8);
        Map<String, Object> result = new HashMap();
        result.put("dataZone", new Long[]{startTime.getTime(), endTime.getTime()});
        return ActionResult.success(result);
    }

    @ApiOperation("遍历显示节点下所以点位")
    @PostMapping({"/getPointByNodeByMsg"})
    public List<PointSyncEntity> getPointByNodeByMsg(@RequestBody ScadaPointPagination scadaPointPagination) {
        List<ScadaNode> nodes = scadaPointPagination.getNodes();
        List<String> codeList = new ArrayList();
        nodes.forEach((t) -> codeList.add(t.getCode()));
        List<PointSyncEntity> listByCode = this.pointSyncService.getListByCode(codeList);
        String type = scadaPointPagination.getType();
        if (!TextUtils.isEmpty(type) && type.equals("1")) {
            listByCode = (List)listByCode.stream().filter((n) -> !n.getType().equals("16")).filter((n) -> !n.getName().isEmpty() || n.getName().contains(scadaPointPagination.getDesc())).filter((n) -> !n.getCode().isEmpty() || n.getCode().contains(scadaPointPagination.getName())).collect(Collectors.toList());
        } else {
            listByCode = (List)listByCode.stream().filter((n) -> !n.getName().isEmpty() || n.getName().contains(scadaPointPagination.getDesc())).filter((n) -> !n.getCode().isEmpty() || n.getCode().contains(scadaPointPagination.getName())).collect(Collectors.toList());
        }

        return listByCode;
    }
}
